package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.model.Document;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	public class ContentStreamService extends EventDispatcher
	{
		private var auth:String;
		
		public function ContentStreamService(auth:String)
		{
			this.auth = auth;
		}
		
		public function getContentStream(document:Document, path:String):void 
		{
			var file:File = new File(path.concat(File.separator).concat(document.fileName));
				
			var fileStream:FileStream = new FileStream();
			
			fileStream.openAsync(file, FileMode.WRITE);
			
			var request:URLRequest = new URLRequest(document.url);
			
			var header:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + auth);
			
			request.requestHeaders.push(header);
			
			var urlStream:URLStream = new URLStream();
			
			urlStream.addEventListener(Event.COMPLETE, finish);
			urlStream.addEventListener(ProgressEvent.PROGRESS, writeBytes);
			
			urlStream.addEventListener(Event.COMPLETE, this.dispatchEvent);
			urlStream.addEventListener(ProgressEvent.PROGRESS, this.dispatchEvent);
			
			urlStream.load(request);
			
			function writeBytes():void
			{
				if (urlStream.bytesAvailable > 51200)
				{
					var dataBuffer:ByteArray = new ByteArray();
	
					urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
					fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
				}
				
			}
			
			function finish():void
			{
				var dataBuffer:ByteArray = new ByteArray();
	
				urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
				fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
				
				fileStream.close();
				urlStream.close();
			}

		}

	}
	
}